package hc.uco.constraints

import java.util.Map;

import org.codehaus.groovy.grails.validation.AbstractConstraint
import org.springframework.validation.Errors

class DependsOnConstraint extends AbstractConstraint {
	private static final String DEFAULT_MESSAGE_CODE = "default.dependson.null.message";
	public static final String DEPENDS_ON_CONSTRAINT = "dependsOn";

	private String field = null;
	private String errorMessageCode = null;

	public void setParameter(Object constraintParameter) {
		if(!(constraintParameter instanceof Map))
			throw new IllegalArgumentException("Parameter for constraint ["
			+DEPENDS_ON_CONSTRAINT+"] of property ["
			+constraintPropertyName+"] of class ["
			+constraintOwningClass+"] must be a map with keys 'field' and 'errorMessageCode'");

		this.field = constraintParameter.get('field', null)
		this.errorMessageCode = constraintParameter.get('errorMessageCode', null)
		super.setParameter(constraintParameter);
	}

	protected void processValidate(Object target, Object propertyValue, Errors errors) {
		System.out.println("DependsOnConstraint:" + this.field + "\n" + this.errorMessageCode);
		if(propertyValue && !target."$field"){
			constraintPropertyName = field;
			def args = (Object[]) [ field, constraintOwningClass, propertyValue	]
			if(this.errorMessageCode){
				super.rejectValue(target, errors, this.errorMessageCode, "not." + DEPENDS_ON_CONSTRAINT, args);
			}else{
				super.rejectValue(target, errors, DEFAULT_MESSAGE_CODE, "not." + DEPENDS_ON_CONSTRAINT, args);
			}
		}
	}

	boolean supports(Class type) {
		// any type
		return true;
	}

	String getName() {
		return DEPENDS_ON_CONSTRAINT;
	}
}